package com.tjtt.tdm.portlet;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.drools.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tjtt.tdm.base.BaseAction;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.base.PubMethod;
import com.tjtt.tdm.flow.service.IWorkflowService;
import com.tjtt.tdm.form.service.IAutoFormService;
import com.tjtt.tdm.portlet.bean.SysPortlet;
import com.tjtt.tdm.portlet.service.PortletService;
import com.tjtt.tdm.system.bean.Role;
import com.tjtt.tdm.system.service.IMessageService;
import com.tjtt.tdm.system.service.RoleService;

public class PortletAction extends BaseAction{

	private PortletService portletService;
	
	/**
	 * 门户新框架
	 * @return
	 */
	public String newPortlet(){
		try {
			String roleid = getRole();
			String[] roleids = roleid.split(",");
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			RoleService roleService =  (RoleService)factory.getBean("roleService");
			String portletids = "";
			for (int i = 0; i < roleids.length; i++) {
				Role role = roleService.findRoleById(Long.parseLong(roleids[i]));
				String portletList = role.getPortletList();
				if(!StringUtils.isEmpty(portletList)){
					portletids += "," + portletList;
				}
			}
			String modules = ""; //m101:{url:"modules/m101.html",	t:"Motivation"},
			String moduleLayout = ""; //"m101:c1:blue", "m102:c2:blue", "m103:c3:blue"
			String columnLayout = ""; //整行显示:: c1:'span-24',  两列显示 
			if(!StringUtils.isEmpty(portletids)){
				portletids = portletids.substring(1);
				List<SysPortlet> list = portletService.getPortletByids(portletids);
				getRequest().setAttribute("portletlist", list);
				int lastcount = 1;
				int nextlocation = 0;//下一个位置点
				for (int i = 0; i < list.size(); i++) {
					SysPortlet portlet = list.get(i);
					if(i != list.size()-1){ 
						nextlocation = list.get(i+1).getLocation().intValue();
					}
					String url="";
					if(portlet.getPortletUrl().indexOf("?")>0){
						url=portlet.getPortletUrl()+"&temp="+Math.random();
					}else {
						url=portlet.getPortletUrl()+"?temp="+Math.random();
					}
					modules += "m"+portlet.getId()+":{url:\""+url+"\",	t:\""+portlet.getPortletName()+"\"},";
					moduleLayout += "\"m"+portlet.getId()+":c"+portlet.getId()+":blue\",";
					if(portlet.getLocation().intValue() == 0){ //整行显示
						columnLayout += "c"+portlet.getId()+":'span-24 last',";
					}else if(portlet.getLocation().intValue() == 1){//一行两列
						if(lastcount == 2){
							lastcount = 1;
							columnLayout += "c"+portlet.getId()+":'span-12 last',";
						}else{
							lastcount++;
							if(i == list.size()-1){
								columnLayout += "c"+portlet.getId()+":'span-12 last',";
							}else if(nextlocation != 1){
								lastcount = 1;
								columnLayout += "c"+portlet.getId()+":'span-12 last',";
							}else{
								columnLayout += "c"+portlet.getId()+":'span-12',";
							}
						}
					}else if(portlet.getLocation().intValue() == 2){//一行三列
						if(lastcount == 3){
							lastcount = 1;
							columnLayout += "c"+portlet.getId()+":'span-8 last',";
						}else{
							lastcount++;
							if(i == list.size()-1){
								columnLayout += "c"+portlet.getId()+":'span-8 last',";
							}else{
								columnLayout += "c"+portlet.getId()+":'span-8',";
							}
						}
					}
				}		
				if(modules.length()>0){
					modules = modules.substring(0,modules.length()-1);
				}
				if(moduleLayout.length()>0){
					moduleLayout = moduleLayout.substring(0,moduleLayout.length()-1);
				}
				if(columnLayout.length()>0){
					columnLayout = columnLayout.substring(0,columnLayout.length()-1);
				}
				getRequest().setAttribute("modules", modules);
				getRequest().setAttribute("moduleLayout", moduleLayout);
				getRequest().setAttribute("columnLayout", columnLayout);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "newportlet";
	}
	/**
	 * 获取页面中的门户
	 * @return
	 */
	public String getPortlet(){
		try {
			String roleid = getRole();
			String[] roleids = roleid.split(",");
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			RoleService roleService =  (RoleService)factory.getBean("roleService");
			String portletids = "";
			for (int i = 0; i < roleids.length; i++) {
				Role role = roleService.findRoleById(Long.parseLong(roleids[i]));
				String portletList = role.getPortletList();
				if(!StringUtils.isEmpty(portletList)){
					portletids += "," + portletList;
				}
			}
			String portletString = "";
			String portletFullString = "";
			if(!StringUtils.isEmpty(portletids)){
				portletids = portletids.substring(1);
				List<SysPortlet> list = portletService.getPortletByids(portletids);
				if(list!=null && list.size()>0){
					if(list.size()==1){
						SysPortlet portlet = list.get(0);
						String url="";
						if(portlet.getPortletUrl().indexOf("?")>0){
							url=portlet.getPortletUrl()+"&temp="+Math.random();
						}else {
							url=portlet.getPortletUrl()+"?temp="+Math.random();
						}
						portletString = "{"+
			            "    width: pageWidth(),\n"+
			            "    portlets: [{\n"+
			            "        attrs: {\n"+
			            "            id: 'portlet"+portlet.getId()+"'\n"+
			            "        },\n"+
			            "        title: '"+portlet.getPortletName()+"',\n"+
			            "        icon: 'ui-icon-signal-diag',\n"+
			            "        content: {\n"+
			            "           style: {\n"+
			            "                height: '"+portlet.getPortletHeight()+"'\n"+
			            "            },\n"+
			            "            type: 'ajax',\n"+
			            "            dataType: 'html',\n"+
			            "            url: '"+url+"',\n"+
			            "            error: function() {\n"+
			            "                $(this).append('<br/><br/>捕获到ajax错误');\n"+
			            "            }\n"+
			            "        },\n"+
			            "        scripts: ['loaded-by-portlet.js']\n"+
			            "    }]\n"+
			            "}\n";
					}else if(list.size()>1){//如果大于1个 则需要分配屏幕大小
						StringBuffer portletLeft = new StringBuffer("{width: pageWidthHalf(),portlets: [");
						StringBuffer portletRight = new StringBuffer("{width: pageWidthHalf(),portlets: [");
						StringBuffer portletFull = new StringBuffer("{width: pageWidth(),portlets: [");
						boolean isfull = false;
						for (int i = 0; i < list.size(); i++) {
							SysPortlet portlet = list.get(i);
							if(portlet.getLocation() == 1){
								String url="";
								if(portlet.getPortletUrl().indexOf("?")>0){
									url=portlet.getPortletUrl()+"&temp="+Math.random();
								}else {
									url=portlet.getPortletUrl()+"?temp="+Math.random();
								}
								portletLeft.append("{"+
								            "        attrs: {\n"+
								            "            id: 'portlet"+portlet.getId()+"'\n"+
								            "        },\n"+
								            "        title: '"+portlet.getPortletName()+"',\n"+
								            "        icon: 'ui-icon-signal-diag',\n"+
								            "        content: {\n"+
								            "           style: {\n"+
								            "                height: '"+portlet.getPortletHeight()+"'\n"+
								            "            },\n"+
								            "            type: 'ajax',\n"+
								            "            dataType: 'html',\n"+
								            "            url: '"+url+"',\n"+
								            "            error: function() {\n"+
								            "                $(this).append('<br/><br/>捕获到ajax错误');\n"+
								            "            }\n"+
								            "        },\n"+
								            "        scripts: ['loaded-by-portlet.js']\n"+
								            "    },\n");
							}else if(portlet.getLocation() == 2){
								String url="";
								if(portlet.getPortletUrl().indexOf("?")>0){
									url=portlet.getPortletUrl()+"&temp="+Math.random();
								}else {
									url=portlet.getPortletUrl()+"?temp="+Math.random();
								}
								portletRight.append("{"+
							            "        attrs: {\n"+
							            "            id: 'portlet"+portlet.getId()+"'\n"+
							            "        },\n"+
							            "        title: '"+portlet.getPortletName()+"',\n"+
							            "        icon: 'ui-icon-signal-diag',\n"+
							            "        content: {\n"+
							            "           style: {\n"+
							            "                height: '"+portlet.getPortletHeight()+"'\n"+
							            "            },\n"+
							            "            type: 'ajax',\n"+
							            "            dataType: 'html',\n"+
							            "            url: '"+url+"',\n"+
							            "            error: function() {\n"+
							            "                $(this).append('<br/><br/>捕获到ajax错误');\n"+
							            "            }\n"+
							            "        },\n"+
							            "        scripts: ['loaded-by-portlet.js']\n"+
							            "    },\n");
							}else if(portlet.getLocation() == 0){//整行显示的
								isfull = true;
								String url="";
								if(portlet.getPortletUrl().indexOf("?")>0){
									url=portlet.getPortletUrl()+"&temp="+Math.random();
								}else {
									url=portlet.getPortletUrl()+"?temp="+Math.random();
								}
								portletFull.append("{"+
							            "        attrs: {\n"+
							            "            id: 'portlet"+portlet.getId()+"'\n"+
							            "        },\n"+
							            "        title: '"+portlet.getPortletName()+"',\n"+
							            "        icon: 'ui-icon-signal-diag',\n"+
							            "        content: {\n"+
							            "           style: {\n"+
							            "                height: '"+portlet.getPortletHeight()+"'\n"+
							            "            },\n"+
							            "            type: 'ajax',\n"+
							            "            dataType: 'html',\n"+
							            "            url: '"+url+"',\n"+
							            "            error: function() {\n"+
							            "                $(this).append('<br/><br/>捕获到ajax错误');\n"+
							            "            }\n"+
							            "        },\n"+
							            "        scripts: ['loaded-by-portlet.js']\n"+
							            "    },\n");
							}
						} 
						if(portletRight.length()>35){
							portletString = portletLeft.substring(0,portletLeft.length()-1) + "]}," + portletRight.substring(0,portletRight.length()-1) + "]}";
						}else{
							portletString = portletLeft.substring(0,portletLeft.length()-1) + "]}";
						}
						if(isfull){
							portletFullString = portletFull.substring(0,portletFull.length()-1) + "]}";
						}else{
							portletFullString = "";
						}
					}
				}
			}
			getRequest().setAttribute("portlet", portletString);
			getRequest().setAttribute("portletFull", portletFullString);
			return "portlet";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}
	/**
	 * 获取待办
	 */
	
	public void queryPortlet(){
		try {
			Map<String, String> filterMap = getPagerMap();
			String userId = this.getUserId();
			String roleId = this.getRole();
			filterMap.put("userId", userId);
			filterMap.put("roleId", roleId);
			filterMap.put("deptId", getDeptid());
			filterMap.put("sidx", "ID");
			filterMap.put("sord", "desc");
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			IWorkflowService workflowService =  (IWorkflowService)factory.getBean("workflowService");
	
			// 查询所有的数据
			PageResult result = workflowService.queryWaitWorkListNew(filterMap);
			StringBuffer sb = new StringBuffer();
			sb.append("<div class=\"info\"><ul class=\"infoList\">");
			for (int i = 0; i < result.getData().size(); i++) {
				Object[] objs = (Object[])result.getData().get(i);
				String date = "";
				if(objs[14]!=null){
					date = String.valueOf(objs[14]).substring(0,19);
				}
				sb.append("<li><b class=\"infoIcon\"></b><a href=\"#\" onclick=\"showDetail('"+objs[0]+"','"+objs[4]+"','"+objs[3]+"','')\">"+objs[1]+"</a>" +
						"<span class=\"date\">["+date+"]</span>" +
						"<span class=\"name\" title=\""+objs[2]+"\">"+objs[2]+"</span><span class=\"name1\" >"+objs[5]+"</span></li>");
			}
			sb.append("</ul></div>");
			PrintWriter out = PubMethod.GetPrintWriter(); 
			out.print(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取待办信息
	 * @return
	 */
	public String getTasks(){
		try {
			Map<String, String> filterMap = getPagerMap();
			String userId = this.getUserId();
			String roleId = this.getRole();
			filterMap.put("userId", userId);
			filterMap.put("roleId", roleId);
			filterMap.put("deptId", getDeptid());
			filterMap.put("sidx", "shiyankssj");
			filterMap.put("sord", "desc");
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			IWorkflowService workflowService =  (IWorkflowService)factory.getBean("workflowService");
	
			// 查询所有的数据
			PageResult result = workflowService.queryWaitWorkListNew(filterMap);
			StringBuffer sb = new StringBuffer();
			sb.append("<div class=\"info\"><ul class=\"infoList\">");
			for (int i = 0; i < result.getData().size()&&i <10; i++) {
				Object[] objs = (Object[])result.getData().get(i);
				sb.append("<li><b class=\"infoIcon\"></b><a href=\"#\" onclick=\"showTasks('"+objs[0]+"')\" style='color:blue;'>"+objs[5]+"</a><span class=\"date\">["+String.valueOf(objs[14]).substring(0, 10)+"]</span>" +
						"<span class=\"name\">"+objs[13]+"</span></li>");
			}
			sb.append("</ul></div>");
			getRequest().setAttribute("message", sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "gtasks";
	}
	
	/**
	 * 获取完成信息
	 * @return
	 */
	public String getWancheng(){
		try {
			Map<String, String> filterMap = getPagerMap();
			String userId = this.getUserId();
			String roleId = this.getRole();
			filterMap.put("userId", userId);
			filterMap.put("roleId", roleId);
			filterMap.put("deptId", getDeptid());
			filterMap.put("sidx", "shiyankssj");
			filterMap.put("sord", "desc");
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			IWorkflowService workflowService =  (IWorkflowService)factory.getBean("workflowService");
	
			// 查询所有的数据
			PageResult result = workflowService.queryWancheng(filterMap);
			StringBuffer sb = new StringBuffer();
			sb.append("<div class=\"info\"><ul class=\"infoList\">");
			for (int i = 0; i < result.getData().size()&&i <10; i++) {
				Object[] objs = (Object[])result.getData().get(i);
				sb.append("<li><b class=\"infoIcon\"></b><a href=\"#\" onclick=\"showWancheng('"+objs[0]+"')\" style='color:blue;'>"+objs[5]+"</a><span class=\"date\">["+String.valueOf(objs[14]).substring(0, 10)+"]</span>" +
						"<span class=\"name\">"+objs[13]+"</span></li>");
			}
			sb.append("</ul></div>");
			getRequest().setAttribute("message", sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "gtasks";
	}
	
	/**
	 * 获取完成信息
	 * @return
	 */
	public String getJinxing(){
		try {
			Map<String, String> filterMap = getPagerMap();
			String userId = this.getUserId();
			String roleId = this.getRole();
			filterMap.put("userId", userId);
			filterMap.put("roleId", roleId);
			filterMap.put("deptId", getDeptid());
			filterMap.put("sidx", "shiyankssj");
			filterMap.put("sord", "desc");
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			IWorkflowService workflowService =  (IWorkflowService)factory.getBean("workflowService");
	
			// 查询所有的数据
			PageResult result = workflowService.queryJinxing(filterMap);
			StringBuffer sb = new StringBuffer();
			sb.append("<div class=\"info\"><ul class=\"infoList\">");
			for (int i = 0; i < result.getData().size()&&i <10; i++) {
				Object[] objs = (Object[])result.getData().get(i);
				sb.append("<li><b class=\"infoIcon\"></b><a href=\"#\" onclick=\"showJinxing('"+objs[0]+"')\" style='color:blue;'>"+objs[5]+"</a><span class=\"date\">["+String.valueOf(objs[14]).substring(0, 10)+"]</span>" +
						"<span class=\"name\">"+objs[13]+"</span></li>");
			}
			sb.append("</ul></div>");
			getRequest().setAttribute("message", sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "gtasks";
	}
	
	/**
	 * 获取完成信息
	 * @return
	 */
	public String getGuoqiyq(){
		try {
			Map<String, String> filterMap = getPagerMap();
			String userId = this.getUserId();
			String roleId = this.getRole();
			filterMap.put("userId", userId);
			filterMap.put("roleId", roleId);
			filterMap.put("deptId", getDeptid());
			filterMap.put("sidx", "shiyankssj");
			filterMap.put("sord", "desc");
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			IAutoFormService autoFormService =  (IAutoFormService)factory.getBean("autoFormService");
	
			// 查询所有的数据
			String strDate = PubMethod.GetNowDateString();
			String strSql = "select * from (select t.yiqimc, t.guigexh, t.xiacidjrq,ceil(MONTHS_BETWEEN(sysdate, to_date(t.xiacidjrq,'YYYY-MM-DD')) * 30) as guoqits " +
					"from kl_yiqi t where t.xiacidjrq < '"+strDate+"' order by t.id desc) where rownum <= 10";
			List lists = autoFormService.getDatabySql(strSql);
			StringBuffer sb = new StringBuffer();
			sb.append("<div class=\"info\"><table style='width:100%;border:0px;'>");
			for (int i = 0; i < lists.size(); i++) {
				Object[] objs = (Object[])lists.get(i);
				sb.append("<tr>");
				sb.append("<td width='120' style='border:0px;'><a href=\"#\" style='text-decoration:none;' onclick=\"showGuoqiyq('"+objs[0]+"')\">"+objs[0]+"</a></td>");
				sb.append("<td width='120' style='border:0px;'>"+objs[1]+"</td>");
				sb.append("<td width='120' style='border:0px;'>"+objs[2]+"</td>");
				sb.append("<td style='border:0px;'>"+objs[3]+"</td>");
				sb.append("</tr>");
			}
			sb.append("</table></div>");
			getRequest().setAttribute("message", sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "gtasks";
	}
	/**
	 * 我的消息
	 */
	public String getMyMessage(){
		try {
			Map<String, String> filterMap = getPagerMap();
			String userId = this.getUserId();
			String roleId = this.getRole();
			filterMap.put("roleId", roleId);
			filterMap.put("sidx", "ID");
			filterMap.put("sord", "desc");
			filterMap.put("tm_notice_type", "1");
			filterMap.put("tm_user_id", userId); 
			filterMap.put("isreceive", "0");
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			IMessageService messageService =  (IMessageService)factory.getBean("messageService");
	
			// 查询所有的数据
			PageResult result = messageService.queryMessage(filterMap);
			StringBuffer sb = new StringBuffer();
			sb.append("<div class=\"info\"><ul class=\"infoList\">");
			for (int i = 0; i < result.getData().size(); i++) {
				Object[] objs = (Object[])result.getData().get(i);
				sb.append("<li><b class=\"infoIcon\"></b><a href=\"#\" onclick=\"showMessage('"+objs[0]+"')\">"+objs[1]+"</a>" +
						"<span class=\"date\">["+String.valueOf(objs[3]).substring(0,19)+"]</span>" +
						"<span class=\"name\">"+objs[2]+"</span></li>");
			}
			sb.append("</ul></div>");
			getRequest().setAttribute("message", sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sysmessage";
	}
 
	/**
	 * 系统公告
	 */
	public String getSystemMessage(){
		try {
			Map<String, String> filterMap = getPagerMap();
			String userId = this.getUserId();
			String roleId = this.getRole();
			filterMap.put("roleId", roleId);
			filterMap.put("sidx", "ID");
			filterMap.put("sord", "desc");
			filterMap.put("tm_notice_type", "0");
			filterMap.put("tm_user_id", userId);
			filterMap.put("isreceive", "0");
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			IMessageService messageService =  (IMessageService)factory.getBean("messageService");
	
			// 查询所有的数据
			PageResult result = messageService.queryGonggao(filterMap);
			StringBuffer sb = new StringBuffer();
			sb.append("<div class=\"info\"><ul class=\"infoList\">");
			for (int i = 0; i < result.getData().size(); i++) {
				Object[] objs = (Object[])result.getData().get(i);
				sb.append("<li><b class=\"infoIcon\"></b><a href=\"#\" onclick=\"showMessage('"+objs[0]+"')\">"+objs[2]+"</a>" +
						"<span class=\"date\">["+String.valueOf(objs[4]).substring(0,19)+"]</span>" +
						"<span class=\"name\">"+objs[3]+"</span></li>");
			}
			sb.append("</ul></div>");
			getRequest().setAttribute("message", sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sysnotice";
	}
	public void getAllPortlet()
	{
		try {
			Map<String, String> filterMap = getPagerMap();
			//取出页面中的查询条件
			String type = getRequest().getParameter("type");
//			String orgParentId = getRequest().getParameter("pId");
			String bid = getRequest().getParameter("id");
			//将查询条件保存到Map里
			String[] viewArray = { "id","portletName","portletUrl","executeType",
					"portletSql","remarks","state","portletHeight"};
			String returnStr = "";
				// 查询所有的数据
				//portletService.getAllPortlet();
				//PageResult result = buildInfoService.queryOrganizationRoomList(filterMap);
				//returnStr = getColumnJson(result, viewArray);
			setContentType();
			PrintWriter out = getResponse().getWriter();
			System.out.println(returnStr);
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	public void quertyPortletList()
	{
		try{
			//String LProjectName = getRequest().getParameter("LProjectName");
			//String LProjectNo = getRequest().getParameter("LProjectNo");
			//String LTypeId = getRequest().getParameter("LTypeId");
			Map filterMap = getPagerMap();
			//filterMap.put("lhProjectName", LProjectName);
			//filterMap.put("lhProjectNo", LProjectNo);
			//filterMap.put("lTypeId", LTypeId);
			String[] viewArray = {"id","portletName","portletUrl","executeType","portletSql","remarks","state","portletHeight","location:[{'0':'整行','1':'一行两列','2':'一行三列'}]","portletSort"};
			//查询所有的数据
			PageResult result =  portletService.queryPortletList(filterMap);
			String returnStr = getColumnJson(result,viewArray);
			setContentType();
			PrintWriter out = getResponse().getWriter();
			out.print(returnStr);	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void addsavePortlet()
	{
		try {
			SysPortlet portlet=new SysPortlet();
			portlet.setPortletName(getRequest().getParameter("portletName"));
			portlet.setExecuteType(getRequest().getParameter("executeType"));
			portlet.setPortletHeight(getRequest().getParameter("portletHeight"));
			portlet.setPortletSql(getRequest().getParameter("portletSql"));
			portlet.setPortletUrl(getRequest().getParameter("portletUrl"));
			portlet.setRemarks(getRequest().getParameter("remarks"));
			portlet.setState(getRequest().getParameter("state"));
			if(getRequest().getParameter("location").isEmpty())
			{
				portlet.setLocation(0l);
			}
			else
			{
				String location=getRequest().getParameter("location");
				location=location.trim();
				if(location.isEmpty())
				{
					portlet.setLocation(0l);
				}
				else 
				{
					portlet.setLocation(Long.parseLong(location));
				}
			}
			if(getRequest().getParameter("portletSort").isEmpty())
			{
				portlet.setPortletSort(0l);
			}
			else
			{
				String portletSort=getRequest().getParameter("portletSort");
				portletSort=portletSort.trim();
				if(portletSort.isEmpty())
				{
					portlet.setPortletSort(0l);
				}
				else
				{
					portlet.setPortletSort(Long.parseLong(portletSort));
				}
			}
			portletService.savePortlet(portlet);
			getRequest().setAttribute("message", "保存成功！");
			PrintWriter out=getResponse().getWriter();
		    out.print("{\"result\":\"success\"}");
		    out.flush();
			out.close();
			} 
			catch (Exception e) {
			e.printStackTrace();
//			getRequest().setAttribute("message", "系统繁忙，请稍后再试！");
			getRequest().setAttribute("message", "添加失败");
		}
	}
	public void deletePortlet() throws Exception{
		PrintWriter out = getResponse().getWriter();
		
		try {
			String ids = getRequest().getParameter("ids");
			List<SysPortlet> orF = portletService.getPortletByids(ids);
			if(ids != null && !ids.isEmpty())
			{
				 portletService.deletePortlet(ids);
			}
			out.print("{\"ajaxResult\":\"success\"}");
		} catch (Exception e) {
			e.printStackTrace();
			out.print("\"ajaxResult\":\"error\"}");
		}
	}
	public void updatePortlet()
	{
		try {
			String id = getRequest().getParameter("id");
			SysPortlet  portlet = portletService.GetPortletById(id);
			portlet.setPortletName(getRequest().getParameter("portletName"));
			portlet.setExecuteType(getRequest().getParameter("executeType"));
			portlet.setPortletHeight(getRequest().getParameter("portletHeight"));
			portlet.setPortletSql(getRequest().getParameter("portletSql"));
			portlet.setPortletUrl(getRequest().getParameter("portletUrl"));
			portlet.setRemarks(getRequest().getParameter("remarks"));
			portlet.setState(getRequest().getParameter("state"));
			if(getRequest().getParameter("location").isEmpty())
			{
				portlet.setLocation(0l);
			}
			else
			{
				String location=getRequest().getParameter("location");
				location=location.trim();
				if(location.isEmpty())
				{
					portlet.setLocation(0l);
				}
				else 
				{
					portlet.setLocation(Long.parseLong(location));
				}
			}
			if(getRequest().getParameter("portletSort").isEmpty())
			{
				portlet.setPortletSort(0l);
			}
			else
			{
				String portletSort=getRequest().getParameter("portletSort");
				portletSort=portletSort.trim();
				if(portletSort.isEmpty())
				{
					portlet.setPortletSort(0l);
				}
				else
				{
					portlet.setPortletSort(Long.parseLong(portletSort));
				}
			}
			portletService.updatePortlet(portlet);
			getRequest().setAttribute("message", "修改成功！");
			PrintWriter out=getResponse().getWriter();
		    out.print("{\"result\":\"success\"}");
		    out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
//			getRequest().setAttribute("message", "系统繁忙，请稍后再试！");
//			return ERROR;
			getRequest().setAttribute("message", "添加失败");
		}
	}
	public String GetPortletById()
	{
		try {
			String lpid = getRequest().getParameter("id");
			SysPortlet lpi=new SysPortlet();
			lpi = portletService.GetPortletById(lpid);
			getRequest().setAttribute("lpi", lpi);
			return "viewPortlet";
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	public PortletService getPortletService() {
		return portletService;
	}
	public void setPortletService(PortletService portletService) {
		this.portletService = portletService;
	}
	
}
